package com.zjut.an.util.system;

import java.io.Serializable;
import java.util.Iterator;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import com.zjut.common.codec.DesUtils;
import com.zjut.zs.applyview.dao.ZsApplyView;
import com.zjut.zs.user.dao.ZsUser;
import com.zjut.zs.userstatus.dao.ZsUserStatus;

public class EncryptInterceptor extends EmptyInterceptor {

	public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		// do nothing
	}

	// This method is called when Employee object gets updated.
	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		if ((entity instanceof ZsUserStatus) || (entity instanceof ZsUser) || (entity instanceof ZsApplyView)) {
			System.out.println("@@" + entity); // 添加数据
			for (int index = 0; index < propertyNames.length; index++) { // 找到名为"身份证"的属性
				System.out.println("@@" + propertyNames[index]);
				if ("usIdcard".equals(propertyNames[index])) { // 使用拦截器将对象的"身份证"属性赋上值
					currentState[index] = DesUtils.encode(String.valueOf(currentState[index]), "s,w,y");
					continue;
				}
			}
		}
		System.out.println("Update Operation");
		return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
	}

	public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		System.out.println("查询操作");
		if ((entity instanceof ZsUserStatus) || (entity instanceof ZsUser) || (entity instanceof ZsApplyView)) {

			// 添加数据
			for (int index = 0; index < propertyNames.length; index++) { // 找到名为"身份证"的属性
				System.out.println("##" + propertyNames[index]);
				if ("usIdcard".equals(propertyNames[index])) {
					System.out.println("解密前:" + state[index]);
					state[index] = DesUtils.decode(String.valueOf(state[index]), "s,w,y");
					System.out.println("解密后:" + state[index]);
				}
			}
		}
		return true;
	}

	// This method is called when Employee object gets created.
	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		System.out.println("Create Operation");
		return false;
	}

	// called before commit into database
	public void preFlush(Iterator iterator) {
		System.out.println("preFlush");
	}

	// called after committed into database
	public void postFlush(Iterator iterator) {
		System.out.println("postFlush");
	}

}
